<?php
//用户管理

namespace App\Services;

use App\Common\CommonConst;
use App\Models\AdminModel;
use App\Repositories\AdminRepository;
use Illuminate\Support\Facades\Auth;

class AdminService
{

    private static $loginErrMaxNum = 3;

    /**
     * 用户登录
     * @param $username
     * @param $password
     * @return array
     */
    public static function login($username = '', $password = '')
    {
        $adminRepo = new AdminRepository();
        if (!$username || !$password) {
            return resultError('请输入账号密码');
        }
        //查询用户名
        $userInfo = AdminModel::where('username', $username)
            ->first();
        if (!$userInfo) {
            return resultError('账号有误');
        } else if ($userInfo['status'] == AdminModel::DISABLED) {
            return resultError('账号被禁用');
        }
        //        if ($userInfo['login_err_num'] >= self::$loginErrMaxNum) {
        //            return resultError('密码错误错误次数过多，请联系灵析管理员重置密码');
        //        }
        //加密密码
//        $encryptPassword = getEncryptPassword($password, $userInfo['salt']);
        $encryptPassword = $password;
        if ($encryptPassword != $userInfo['password']) {
            //记录登录错误次数
            $adminRepo->incrLoginErrNum($userInfo['id']);
            return resultError('密码有误');
        }
        //登录成功，重置错误次数
        $adminRepo->incrLoginErrNum($userInfo['id'], true);
        //生成密钥
        Auth::setUser($userInfo);
        $token = $userInfo->createToken(CommonConst::PLATFORM_ADMIN);

        $output = [
            'token'      => $token->plainTextToken,
            'token_type' => 'Bearer',
        ];

        return resultSuccess($output, '登录成功');
    }
}
